package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.constant.ProductConstant;
import com.atguigu.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.dao.AttrGroupDao;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimall.product.entity.AttrEntity;
import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.AttrService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.AttrRespVo;
import com.atguigu.gulimall.product.vo.AttrVo;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Autowired
    AttrDao attrDao;

    @Autowired
    AttrGroupDao attrGroupDao;

    @Autowired
    CategoryDao categoryDao;

    @Autowired
    CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attrVo){
        //先保存attr表的数据
        AttrEntity attrEntity = new AttrEntity();
        //attr_id 这个值是上送的还是数据库直接自增吗？
//        BeanUtils.copyProperties(attrVo,attrEntity);
        attrEntity.setAttrId(attrVo.getAttrId());
        attrEntity.setAttrName(attrVo.getAttrName());
        attrEntity.setSearchType(attrVo.getSearchType());
        attrEntity.setValueType(attrVo.getValueType());
        attrEntity.setIcon(attrVo.getIcon());
        attrEntity.setValueSelect(attrVo.getValueSelect());
        attrEntity.setAttrType(attrVo.getAttrType());
        attrEntity.setEnable(attrVo.getEnable());
        attrEntity.setCatelogId(attrVo.getCatelogId());
        attrEntity.setShowDesc(attrVo.getShowDesc());
        this.save(attrEntity);

        //type==1 只保存base属性的关联表数据
        if (attrVo.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            //再保存关联表的数据
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            //查id
            QueryWrapper<AttrEntity> eq = new QueryWrapper<AttrEntity>()
                    .eq("attr_name", attrEntity.getAttrName()).eq("catelog_id", attrEntity.getCatelogId());
            Long attrId = attrDao.selectOne(eq).getAttrId();
            attrAttrgroupRelationEntity.setAttrId(attrId);
            attrAttrgroupRelationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
        }



    }

    //规格参数列表查询
    @Override
    public PageUtils qeuryBaseAttrPage(Map<String, Object> params, Long catlogId, String type) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
        //1:0
        queryWrapper.eq("attr_type","base".equalsIgnoreCase(type)?ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode():ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        //选中三级菜单，就根据所属分类Id查询
        if (catlogId != 0){
            queryWrapper.eq("catelog_id",catlogId);
        }
        //左侧列表没有选中三级菜单catlogId==0，代表查全部
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            queryWrapper.and((wrapper) -> {
                wrapper.eq("attr_id",key).or().like("attr_name",key);
            });
        }

        //转换list
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        //取出list集合，换成另一个list，原list少字段
        List<AttrEntity> records = page.getRecords();
        //collect(Collectors.toList()) 拿到新的List对象
        List<AttrRespVo> respVoList = records.stream().map((attrEntity -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);
            //所属分组名字
            /*
                (1).根据attr_id查表pms_attr_attrgroup_relation取出attr_group_id
                (2).根据attr_group_id查表pms_attr_group取出attr_group_name
             */

            //基本属性bese才设置分组信息
            //如果是销售属性是不存在分组的，所以要判断是销售属性->设置分组名
            if ("base".equalsIgnoreCase(type)){
                AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao
                        .selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                if (relationEntity != null && relationEntity.getAttrGroupId() != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                    //groupName
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }

            //所属分类名字
            /*
                根据AttrEntity对象catlogId（也就是pms_category表的主键cat_id）查表pms_category的name（也就是catlogName）
             */
            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                //catlogName
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            return attrRespVo;
            //collect(Collectors.toList())取出新的list,返回给page
        })).collect(Collectors.toList());
        pageUtils.setList(respVoList);
        return pageUtils;
    }

    @Cacheable(value = "attr", key = "'attrinfo' + #root.args[0]")
    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrEntity attrEntity = attrDao.selectById(attrId);
        AttrRespVo attrRespVo = new AttrRespVo();
        //groupName,catelogPath,catlogName
        BeanUtils.copyProperties(attrEntity,attrRespVo);

        //基本属性才设置分组名，销售属性没有展示分组名
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            //1.设置分组信息
            AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao
                    .selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if (relationEntity != null) {
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                if (attrGroupEntity != null){
                    //groupName
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }

        //catelogPath: [2, 34, 225]
        Long[] catelogPath = categoryService.findCatelogPath(attrEntity.getCatelogId());
        attrRespVo.setCatelogPath(catelogPath);

        //2.设置分类信息
        //catlogName
        CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
        if (categoryEntity != null) {
            //catlogName
            attrRespVo.setCatelogName(categoryEntity.getName());
        }

        return attrRespVo;
    }

    @Transactional
    @Override
    public void updateAttr(AttrVo attrVo) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo,attrEntity);
        this.updateById(attrEntity);

        //attr_type=base&&选择了分组attr_group_id 才修改关联分组
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attrVo.getAttrGroupId() != null) {
            //修改关联分组
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            relationEntity.setAttrId(attrVo.getAttrId());
            Integer count = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrVo.getAttrId()));
            //count>0证明有数据，可以修改，count<0表示没有数据就走新增操作
            if (count > 0) {
                attrAttrgroupRelationDao.update(relationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrVo.getAttrId()));
            } else {
                attrAttrgroupRelationDao.insert(relationEntity);
            }
        }

    }

    //获取属性分组-指定分组关联的所有属性
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        List<AttrEntity> list = new ArrayList<>();
        List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationDao
                .selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        if (relationEntities == null || relationEntities.size() == 0){
            return list;
        }
        //方式1:增强for
//        List<AttrEntity> entities = new ArrayList<>();
//        for (AttrAttrgroupRelationEntity relationEntity : relationEntities) {
//            AttrEntity attrEntity = attrDao.selectById(relationEntity.getAttrId());
//            entities.add(attrEntity);
//        }
//        return entities;

        //方式2：Stream流API
        List<Long> attrIds = relationEntities.stream().map(relationEntitie -> {
            return relationEntitie.getAttrId();
        }).collect(Collectors.toList());
        list = this.listByIds(attrIds);
        return list;
    }


    //查出可以关联的属性
    //获取属性分组里面还没有关联的本分类里面的其他基本属性，方便添加新的关联
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
        IPage<AttrEntity> page = new Query<AttrEntity>().getPage(params);
        //查出当前分类(catelog_id)下，所有attr_group_id,拿到attr_id,然后筛选掉当前分组attr_group_id的attr_id
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectOne(new QueryWrapper<AttrGroupEntity>().eq("attr_group_id", attrgroupId));
        Long catelogId = attrGroupEntity.getCatelogId();
        List<AttrGroupEntity> groupEntities = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        //取出当前分类下的所有attr_group_id
        List<Long> attrGroupIds = groupEntities.stream().map((item) -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());
        //查关联表relation 排除属性分组attr_group_id=？
        List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", attrGroupIds));
        //如果未查到关联表数据就返回Null
        if (relationEntities.size() == 0 || relationEntities ==null){
            PageUtils pageUtils = new PageUtils(page);
            pageUtils.setList(null);
            return pageUtils;
        }
        //取出attr_ids
        List<Object> attrIds = relationEntities.stream().map((relation) -> {
            return relation.getAttrId();
        }).collect(Collectors.toList());

        //筛选条件 attrIds,catelog_id,attr_type + key查询（attr_id,attr_name）
        QueryWrapper<AttrEntity> attrEntityQueryWrapper = new QueryWrapper<>();
        if (attrIds != null && attrIds.size() > 0){
            attrEntityQueryWrapper.notIn("attr_id",attrIds);
        }
        attrEntityQueryWrapper.eq("catelog_id",catelogId);
        attrEntityQueryWrapper.eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            attrEntityQueryWrapper.and((wrapper)->{
                wrapper.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> iPage = this.page(page, attrEntityQueryWrapper);
        return new PageUtils(iPage);
    }

}